package com.bw.user.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName LoginInterceptor
 * @Author Hao_YunKai
 * @Date 2022/3/25 20:17
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    // 更新cookie过期时间
                    cookie.setMaxAge(0); //删除 cookie
                    cookie.setPath("/"); //创建时设置了什么参数，删除时就要设置什么参数
                    Cookie cookie1 = new Cookie("token",cookie.getValue());
                    cookie1.setMaxAge(60 * 30);
                    cookie1.setPath("/");
                    response.addCookie(cookie);
                    response.addCookie(cookie1);
                    String userRedis = redisTemplate.opsForValue().get(cookie.getValue());
                    // 判断redis是否有值
                    if (userRedis != null) {
                        // 更新redis过期时间
                        redisTemplate.delete(cookie.getValue());
                        redisTemplate.opsForValue().set(cookie.getValue(), userRedis, 30, TimeUnit.MINUTES);
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        }

        // cookie失效了
        response.sendRedirect("/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
